package cn.lizemin.service.impl;

import cn.lizemin.dao.UserDao;
import cn.lizemin.entity.User;
import cn.lizemin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import java.nio.charset.StandardCharsets;

/**
 * @author lzm
 * @version 1.0
 * @description: TODO
 * @date 2022/1/2 13:54
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {
    private UserDao userDao;

    @Autowired
    public UserServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public void register(User user) {
//        1.根据用户查询数据库是否存在该用户名
        User userDB = userDao.findByUserName(user.getUsername());
//        2.如果存在报错：用户名已经存在
        if (!ObjectUtils.isEmpty(userDB)) throw new RuntimeException("用户名已存在！");
//        3.如果不存在则注册
        String passwordSecret = DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8));
        user.setPassword(passwordSecret);
        userDao.save(user);

    }

    @Override
    public User login(String username, String password) {
//        1.根据用户名查询用户是否存在
        User user = userDao.findByUserName(username);
        if (ObjectUtils.isEmpty(user)) throw new RuntimeException("用户名输入错误！");
        String digestPassword = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        if (!user.getPassword().equals(digestPassword)) throw new RuntimeException("密码错误！");
        return user;
    }
}
